<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta http-equiv="X-UA-Compatible" content="IE=edge" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>节流</title>
  </head>
  <body>
    <div style="height: 200vh; background-color: skyblue"></div>
    <script>
      // 浅谈 JS 防抖和节流(https://segmentfault.com/a/1190000018428170)
      function showTop() {
        var scrollTop =
          document.body.scrollTop || document.documentElement.scrollTop
        console.log('滚动条位置：' + scrollTop)
      }
      window.onscroll = throttle(showTop, 1000)

      /*
       * 节流
       * 一段时间内,只能执行一次
       */
      function throttle(fn, delay) {
        let valid = true
        return function () {
          if (!valid) return false

          valid = false
          setTimeout(() => {
            fn()
            valid = true
          }, delay)
        }
      }
    </script>
  </body>
</html>
